﻿Imports System.Net
Imports System.IO
Imports SACommon

Public Class ucCleanFTP
    Private mFTPFiles As FTPFile
    Private Async Sub ucCleanFTP_Load(sender As Object, e As EventArgs) Handles Me.Load

        gApp.SetAppVariables()

        lvwAppFiles.Columns(0).AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)
        lvwAppFiles.Columns(1).AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)
        lvwAppFiles.Columns(2).AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)
        lvwAppFiles.Columns(3).AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)
        lvwAppFiles.Columns(4).AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)
        lvwAppFiles.Columns(5).AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)

        Extensions = New Dictionary(Of [String], [String])()
        Extensions.Add("yes", "Match")
        Extensions.Add("no", "Do Not Match")

        For Each kvp As KeyValuePair(Of [String], [String]) In Extensions
            lvwAppFiles.Groups.Add(kvp.Key, kvp.Value)
        Next

        Messenger.SendMessage(Messenger.MessageType.GeneralMessage, "Getting FTP Files ...", True)
        Application.DoEvents()
        Await LoadFTPDirectory()
        If lvwAppFiles.Items.Count = 0 Then Messenger.SendMessage(Messenger.MessageType.GeneralMessage, "No files found", True)
    End Sub

#Region "FTP"
    Async Function LoadFTPDirectory() As Task
        Messenger.SendMessage(Messenger.MessageType.UpdateStart, "", True)

        mFTPFiles = New FTPFile

        Dim tFTPFile As FTPFile.FTPFileItem
        Dim sf() As String
        Dim pos As Integer

        ' Get the object used to communicate with the server.
        Dim request As FtpWebRequest = DirectCast(WebRequest.Create(gApp.FTPFileUpdateFolder), FtpWebRequest)
        request.Method = WebRequestMethods.Ftp.ListDirectoryDetails

        ' This example assumes the FTP site uses anonymous logon.
        request.Credentials = New NetworkCredential(gUDApp.SelectedApp.FTPUsername, gUDApp.SelectedApp.FTPPassword)

        'Ensure the FTP directory exists


        Dim response As FtpWebResponse = Await request.GetResponseAsync()

        Dim responseStream As Stream = response.GetResponseStream
        Dim reader As New StreamReader(responseStream)

        Dim s As String = reader.ReadToEnd
        sf = s.Split(vbCr)

        For Each item In sf
            If item.Trim <> "" Then
                tFTPFile = New FTPFile.FTPFileItem
                pos = InStr(item.Trim, " ")
                tFTPFile.FileDate = Strings.Left(item.Trim, pos).Trim
                item = Strings.Right(item.Trim, item.Trim.Length - pos).Trim
                pos = InStr(item.Trim, " ")
                tFTPFile.FileTime = Strings.Left(item.Trim, pos).Trim
                item = Strings.Right(item.Trim, item.Trim.Length - pos).Trim
                pos = InStr(item.Trim, " ")
                tFTPFile.FileSize = CInt(Strings.Left(item.Trim, pos))
                tFTPFile.FileName = Strings.Right(item.Trim, item.Trim.Length - pos).Trim
                tFTPFile.Match = False
                mFTPFiles.Add(tFTPFile)
            End If
        Next

        reader.Close()
        response.Close()

        LoadAppFiles()
        Messenger.SendMessage(Messenger.MessageType.UpdateEnd, "", True)
    End Function
    Function CleanFTPFiles(Filename As String) As String
        Dim request As FtpWebRequest = DirectCast(WebRequest.Create(String.Format("{0}/{1}", gApp.FTPFileUpdateFolder, Filename)), FtpWebRequest)

        'If you need to use network credentials
        request.Credentials = New NetworkCredential(gUDApp.SelectedApp.FTPUsername, gUDApp.SelectedApp.FTPPassword)
        'additionally, if you want to use the current user's network credentials, just use:
        'System.Net.CredentialCache.DefaultNetworkCredentials

        request.Method = WebRequestMethods.Ftp.DeleteFile
        Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
        Return response.StatusDescription
        response.Close()
    End Function
#End Region
#Region "Load Files"
    Sub LoadAppFiles()
        Dim tMatch As Boolean
        UseWaitCursor = True
        lvwAppFiles.Items.Clear()

        lvwAppFiles.BeginUpdate()

        Dim tString As String
        Dim tFullname As String

        For Each item In mFTPFiles.FTPFiles
            tMatch = True

            Dim lvi As ListViewItem = lvwAppFiles.Items.Add(item.FileName)

            lvi.SubItems.Add(item.FileDate)
            lvi.SubItems.Add(item.FileTime)
            Dim t As String = item.FileSize
            t = GeneralFunctions.ToFileSizeString(item.FileSize)
            lvi.SubItems.Add(GeneralFunctions.ToFileSizeString(item.FileSize))

            tString = FindMatch(item.FileName)

            item.Match = CBool(Strings.Left(tString.Trim, 1))
            tFullname = Strings.Right(tString.Trim, tString.Trim.Length - 1)

            If item.Match = True Then
                tString = "yes"
            Else
                tString = "no"
                lvi.Checked = True
            End If

            lvi.SubItems.Add(tString)
            lvi.SubItems.Add(tFullname)
            lvi.Tag = item.FileName
            lvi.Group = lvwAppFiles.Groups(tString)
        Next

        lvwAppFiles.Columns(0).Width = -1
        lvwAppFiles.Columns(1).Width = -1
        lvwAppFiles.Columns(2).Width = -1
        lvwAppFiles.Columns(3).Width = -1
        lvwAppFiles.Columns(3).TextAlign = HorizontalAlignment.Right
        lvwAppFiles.Columns(4).Width = -2
        lvwAppFiles.Columns(5).Width = -2

        lvwAppFiles.EndUpdate()

        UseWaitCursor = False
    End Sub
    Function FindMatch(Filename As String) As String
        'For Each ap In gAppFile.AppFileList
        '    If (ap.UniqueFilename & ".ZIP").ToUpper = Filename.ToUpper Then Return True
        'Next
        Dim a = From x In gAppFile.AppFileList Where (x.UniqueFilename & ".ZIP").ToUpper = Filename.ToUpper And x.IncludeStatus = True
        If a.Count > 0 Then
            If a.First.IncludeStatus = True Then
                Return "1" & a.First.Fullname
            Else
                Return "0" & a.First.Fullname
            End If
        End If
        Return "0"
    End Function
#End Region
#Region "Properties"
    Public Property Extensions() As Dictionary(Of [String], [String])
        Get
            Return m_Extensions
        End Get
        Private Set(value As Dictionary(Of [String], [String]))
            m_Extensions = value
        End Set
    End Property
    Private m_Extensions As Dictionary(Of [String], [String])
#End Region
#Region "Process UI"
    Private Async Sub btnAppAdd_Click(sender As Object, e As EventArgs) Handles btnAppAdd.Click
        Dim s As String
        For z As Int32 = 0 To lvwAppFiles.Items.Count - 1
            If lvwAppFiles.Items(z).Checked = True Then
                s = CleanFTPFiles(lvwAppFiles.Items(z).Text)

                If Strings.Left(s.Trim, 3) = "250" Then
                    lvwAppFiles.Items(z).ImageIndex = Utils.FTPImageIndex.Success
                Else
                    lvwAppFiles.Items(z).ImageIndex = Utils.FTPImageIndex.DelError
                End If
                lvwAppFiles.Items(z).SubItems(5).Text = s
                Application.DoEvents()
            End If
        Next
        Await LoadFTPDirectory()
    End Sub
#End Region
End Class
